

#import "XHNetworking.h"
#import <CommonCrypto/CommonDigest.h>




#ifdef DEBUG
#define DebugLog(...) NSLog(__VA_ARGS__)
#else
#define DebugLog(...)
#endif


#pragma mark-@interface XHNetworkCache

@interface XHNetworkCache()

//@property (nonatomic, strong) HKTShowNetworkView* networkViewModel;

@end

@implementation XHNetworkCache

@end

#pragma mark- @interface XHNetworking

@interface XHNetworking()



@end

@implementation XHNetworking

+ (NSMutableURLRequest*)createManagerWithURL:(NSString*)url withStr:(NSString*)str
{
    NSLog(@"传给后台的body = %@",str);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.timeoutInterval = 30;
    request.HTTPMethod = @"POST";
    //2.设置请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //3.设置请求体
    //    NSError* error = [[NSError alloc]init];
    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = data;
    return request;
}

+ (NSMutableURLRequest*)createManagerWithURL:(NSString*)url withDict:(NSDictionary*)dict
{
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.timeoutInterval = 60;
    request.HTTPMethod = @"POST";
    //2.设置请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //3.设置请求体
    NSString* str = [JSONToString dictionaryToJson:dict];
    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = data;
    return request;
}

/**
 *  POST请求
 */
+ (void)POST:(NSString *)URL parameters:(NSDictionary *)dic  success:(httpRequestSucess)success failure:(httpRequestFailed)failure
{
        [SVProgressHUD showInfoWithStatus:@""];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        NSMutableURLRequest* request = [self createManagerWithURL:URL withDict:dic];
        NSURLSessionDataTask* dataTask = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSHTTPURLResponse* newResponse = (NSHTTPURLResponse*)response;
            if (newResponse.statusCode == 200)
            {
                NSLog(@"网络正常.....................");
                if (data)
                {
                    [XHNetworking removeProgress];
                    success(data);
                }
                else
                {
                    [XHNetworking removeProgress];
                }
            }
            else
            {
                [XHNetworking removeProgress];
                if (error.code == -1009)
                {
                    failure(error);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                        [statusBar showStatusMessage:@"检测到您的设备没有连接网络！"];
                    });
                }
                else if (error.code == -1001)
                {
                    failure(error);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                        [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    });
                }
                else
                {
                    failure(error);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                        [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    });
                }
            }
        }];
        [dataTask resume];
}

+ (void)removeProgress
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    });
}

/**
 *  POST请求,自动缓存
 */
+ (void)POST:(NSString *)URL parameters:(NSDictionary *)dic cacheStr:(NSString*)str jsonCache:(httpRequestCache)jsonCache  success:(httpRequestSucess)success failure:(httpRequestFailed)failure;
{
    [SVProgressHUD showInfoWithStatus:@""];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSMutableURLRequest* request = [self createManagerWithURL:URL withDict:dic];
    NSURLSessionDataTask* dataTask = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse* newResponse = (NSHTTPURLResponse*)response;
        if (newResponse.statusCode == 200)
        {
            NSLog(@"网络正常.....................");
            if (data)
            {
                [XHNetworking removeProgress];
                //保存请求回来的数据
                id result = [CacheData getCache:str];
                if (result == nil || ![result isKindOfClass:[NSData class]])
                {
                    [CacheData saveCache:str andCache:data];
                }
                else
                {
                    //把json转化为字符串
                    NSString* str1 = [CacheData convertToJSONData:result];//本地
                    NSString* str2 = [CacheData convertToJSONData:data];
                    //把本地的json和获取的json进行比较
                    if (![str2 isEqualToString:str1])
                    {
                        //如果本地数据和获取的网络json数据是不一样的，就更新本地数据
                        [CacheData saveCache:str andCache:data];
                    }
                }
                //再从本地读取json
                result = [CacheData getCache:str];
                if (result != nil && [result isKindOfClass:[NSData class]])
                {
                    success(result);
                }
            }
            else
            {
                [XHNetworking removeProgress];
            }
        }
        else
        {
            [XHNetworking removeProgress];
            //无网络情况下 ，调取缓存
            //保存请求回来的数据
            id cache = [CacheData getCache:str];
            if (cache != nil && [cache isKindOfClass:[NSData class]])
            {
                //回调缓存
                jsonCache(cache);
            }
            
            if (error.code == -1009)
            {
                failure(error);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"检测到您的设备没有连接网络!"];
                });
            }
            else if (error.code == -1001)
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    
                });
            }
            else
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    
                });
            }
            
        }
    }];
    [dataTask resume];
}


/**
 *  线下保单POST请求,自动缓存
 */
+ (void)POSTXXBD:(NSString *)URL parameters:(NSString*)jsonStr cacheStr:(NSString*)str jsonCache:(httpRequestCache)jsonCache  success:(httpRequestSucess)success failure:(httpRequestFailed)failure
{
    [SVProgressHUD showInfoWithStatus:@""];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSMutableURLRequest* request = [self createManagerWithURL:URL withStr:jsonStr];
    NSURLSessionDataTask* dataTask = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse* newResponse = (NSHTTPURLResponse*)response;
        if (newResponse.statusCode == 200)
        {
            NSLog(@"网络正常.....................");
            if (data)
            {
                [XHNetworking removeProgress];
                //保存请求回来的数据
                id result = [CacheData getCache:str];
                if (result == nil || ![result isKindOfClass:[NSData class]])
                {
                    [CacheData saveCache:str andCache:data];
                }
                else
                {
                    //把json转化为字符串
                    NSString* str1 = [CacheData convertToJSONData:result];//本地
                    NSString* str2 = [CacheData convertToJSONData:data];
                    //把本地的json和获取的json进行比较
                    if (![str2 isEqualToString:str1])
                    {
                        //如果本地数据和获取的网络json数据是不一样的，就更新本地数据
                        [CacheData saveCache:str andCache:data];
                    }
                }
                //再从本地读取json
                result = [CacheData getCache:str];
                if (result != nil && [result isKindOfClass:[NSData class]])
                {
                    success(result);
                }
                
            }
            else
            {
                [XHNetworking removeProgress];
            }
        }
        else
        {
            
            [XHNetworking removeProgress];
            //无网络情况下 ，调取缓存
            //保存请求回来的数据
            id cache = [CacheData getCache:str];
            if (cache != nil && [cache isKindOfClass:[NSData class]])
            {
                //回调缓存
                jsonCache(cache);
                
            }
            
            if (error.code == -1009)
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"检测到您的设备没有连接网络!"];
                    
                });
            }
            else if (error.code == -1001)
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    
                });
            }
            else
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    
                });
            }
        }
    }];
    [dataTask resume];
}



/**
 *  GET请求
 */
+ (void)GET:(NSString *)URL parameters:(NSDictionary *)dic success:(httpRequestSucess)success failure:(httpRequestFailed)failure
{
    [SVProgressHUD showInfoWithStatus:@""];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
    NSURLSessionDataTask* dataTask = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse* newResponse = (NSHTTPURLResponse*)response;
        if (newResponse.statusCode == 200)
        {
            NSLog(@"网络正常.....................");
            if (data)
            {

                [XHNetworking removeProgress];
                success(data);
            }
            else
            {
                [XHNetworking removeProgress];
            }
        }
        else
        {
            [XHNetworking removeProgress];
            if (error.code == -1009)
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"检测到您的设备没有连接网络!"];

                    
                });
            }
            else if (error.code == -1001)
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"无法获取到相关数据！"];

                    
                });
            }
            else
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    
                });
            }
        }
    }];
    [dataTask resume];
}

/**
 *  GET请求,自动缓存。
 */
+ (void)GET:(NSString *)URL parameters:(NSDictionary *)dic cacheStr:(NSString*)str jsonCache:(httpRequestCache)jsonCache success:(httpRequestSucess)success failure:(httpRequestFailed)failure
{
    [SVProgressHUD showInfoWithStatus:@""];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    //回调缓存
    //    jsonCache([XHNetworkCache cacheJsonWithURL:URL]);
    jsonCache([CacheData getCache:str]);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
    NSURLSessionDataTask* dataTask = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse* newResponse = (NSHTTPURLResponse*)response;
        if (newResponse.statusCode == 200)
        {
            NSLog(@"网络正常.....................");
            if (data)
            {
                [XHNetworking removeProgress];
                success(data);
            }
            else
            {
                [XHNetworking removeProgress];
            }
        }
        else
        {
            [XHNetworking removeProgress];
            if (error.code == -1009)
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"检测到您的设备没有连接网络!"];
                    
                });
            }
            else if (error.code == -1001)
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    
                });
            }
            else
            {
                failure(error);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"无法获取到相关数据！"];
                    
                });
            }
        }
    }];
    [dataTask resume];
}

@end
